'use strict';
const jwt = require('jsonwebtoken');
module.exports = (opt = {}) => {
  return async (ctx, next) => {
    // verify token
    const ignores = opt.ignore || [];
    try {
      for (const ignore of ignores) {
        if (ctx.url.indexOf(ignore) >= 0) {
          return await next();
        }
      }
      if (ctx.query.test) {
        ctx.author = await ctx.service.test.author(ctx.query.test);
        try {
          return await next();
        } catch (e) {
          throw new Error(`API异常：${JSON.stringify(e.stack)}`);
        }
      }
      const token = ctx.get('token');
      console.log('ctx.token', token);
      if (token) {
        const identify = ctx.app.config.identify;
        ctx.author = jwt.verify(token, identify.identification);
        try {
          return await next();
        } catch (e) {
          throw new Error('API异常');
        }
      }
      throw new Error('认证字段缺失');
    } catch (error) {
      ctx.status = 403;
      const response = { error: error.message };
      switch (error.name) {
        case 'TokenExpiredError':
          ctx.status = 401;
          response.message = '认证过期,请重新登录';
          response.errcode = ctx.app.ERRCODE.AUTH_EXPIRE;
          break;
        case 'JsonWebTokenError':
          response.errcode = ctx.app.ERRCODE.AUTH_FAIL;
          response.message = '认证失败,请重新登录';
          break;
        default:
          response.errcode = ctx.app.ERRCODE.AUTH_ERROR;
          response.message = error.message;
          break;
      }
      ctx.body = response;
    }
  };
};
